/**
 * Created by gaoyj on 2018/6/30.
 */
window.onload = function (ev) {
    topbar.hide();
};
var myDate = new Date();
var month = myDate.getMonth() + 1;
var day = myDate.getDate();
if (month < 10) {
    month = "0" + month;
}
if (day < 10) {
    day = "0" + day;
}
var _start = myDate.getFullYear() + '-' + month + '-' + day;
var _end = myDate.getFullYear() + '-' + month + '-' + day;
laydate.render({
    elem: '#startTime'
});
laydate.render({
    elem: '#endTime' //指定元素
});
var addUserForm = $("#addUserForm").validate({
    rules: {
        account: {
            required: true,
        },
        dailySupplyLimit: {
            required: true,
        }
    }
});
jQuery.validator.addMethod("aliPayAccountCheck", function (value, element) {
    var regTel = /^[1][3,4,5,7,8][0-9]{9}$/;
    var reEmail = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/;
    return this.optional(element) || (regTel.test(value)) || (reEmail.test(value));
}, "支付宝账号格式有误");
//初始化佣金展示开关状态
commissionStatusAuditGet();
//销卡模板
var str;
$.post("productPrice/findModelPrice", {param: true}, function (data) {
    var group_obj = data;
    for (var i = 0; i < group_obj.length; i++) {
        str += '<option value="' + group_obj[i].id + '">' + group_obj[i].modelName + '</option>'
    }
    $("#supplyModel").append(str);
    $("#editSupplyModel").append(str);
});
buttonShiro("export_Role");
var adminRole = roleCheck();
$('#dataTable').bootstrapTable({
    url: '/UserController/getUser',
    height: $(window).height() - 200,
    pageSize: 30,
    pagination: true,
    pageList: [30, 50, 100],
    clickToSelect: true,
    queryParams: queryParams,
    queryParamsType: '',
    sidePagination: 'server',
    detailView: true,
    responseHandler: function (res) {
        return {
            "total": res.total,//总页数
            "rows": res.resultList   //数据
        };
    },
    onClickRow: function (row, $element) {
        if (row.account != null && row.account != '') {
            $("#account_field" + row.account).html(row.account);
        }
    },
    onExpandRow: function (index, row, $detail) {
        InitSubTable(index, row, $detail);
    },
    columns: [[
        {
            checkbox: true
        },
        {
            width: '3px',
            align: 'center',
            formatter: function (v, row, index) {
                return index + 1
            }
        },
        {
            title: '会员ID',
            field: 'userId',
            width: 90,
            align: 'center',
            visible: false
        },
        {
            title: '会员编号',
            field: 'account',
            width: 100,
            align: 'center',
            formatter: function (v, row, index) {
                return copyAddon(v) + (adminRole == 1 ? v : userAccountHidden(row.account, row.account));
            }
        },
        {
            title: '会员名称',
            field: 'supInfo.name',
            width: 190,
            align: 'center',
            formatter: function (v, row, index) {
                if (row.isPrivatePrice === null || row.isPrivatePrice === 0) {
                    return v;
                }
                return "<span style='color:red;'>" + v + "</span>";
            }
        },
        {
            title: '状态',
            field: 'status',
            width: 100,
            align: 'center',
            formatter: function (v, row, index) {
                return userStatus[v];
            }
        },
        {
            title: '供卡接口状态',
            field: 'apiState',
            width: 100,
            align: 'center',
            formatter: function (v, row, index) {
                return userStatus[v];
            }
        },
        {
            title: '每日提卡限制',
            field: 'dailySupplyLimit',
            width: 100,
            align: 'center'
        },
        {
            title: '限制类型',
            field: 'entityLimit',
            width: 100,
            align: 'center',
            formatter: function (v, row, index) {
                return {"true": "实体卡", "false": "电子卡"}[v];
            }
        },
        {
            title: '供卡审核状态',
            field: 'submitCardApply',
            width: 100,
            align: 'center',
            formatter: function (v, row, index) {
                if (v === "AUDITING") {
                    return "<span style='color:" + submitCardApplyObj[v]['color'] + ";text-decoration: underline;cursor: pointer' onclick='fixSubmitApply(" + row.userId + ")'>" + submitCardApplyObj[v]['font'] + "</span>";
                } else {
                    return "<span style='color: " + submitCardApplyObj[v]['color'] + "'>" + submitCardApplyObj[v]['font'] + "</span>";
                }
            }
        },
        {
            title: '销卡模板',
            field: 'modelName',
            width: 100,
            align: 'center'
        },
        {
            title: 'PM',
            field: 'userPm.name',
            width: 100,
            align: 'center'
        },
        {
            title: '注册时间',
            field: 'registeTime',
            width: 100,
            align: 'center',
            formatter: function (v, row, index) {
                return format(v);
            }
        },
        {
            title: '会员来源',
            field: 'type',
            width: 70,
            align: 'center',
            formatter: function (v, row, index) {
                return userType[v];
            }
        },
        {
            title: '绑定IP',
            field: 'ip',
            width: '80px',
            align: 'center'
        },
        {
            title: '权益信用分',
            field: 'equityCredit',
            width: '80px',
            align: 'center'
        }
    ]]
})

var InitSubTable = function (index, row, $detail) {
    var cur_table = $detail.html('<table></table>').find('table');
    $(cur_table).bootstrapTable({
        url: '/UserController/queryUserRecordPage',
        queryParams: function (params) {
            var temp = {
                userId: row.userId,
                size: params.pageSize,
                page: params.pageNumber,
            };
            return temp;
        },
        clickToSelect: true,
        detailView: false,//父子表
        queryParamsType: '',
        pagination: true,
        pageSize: 5,
        pageList: [5, 10],
        sidePagination: 'server',
        detailView: false,
        responseHandler: function (res) {
            return {
                "total": res.total,//总页数
                "rows": res.resultList   //数据
            };
        },
        columns: [
            {
                field: 'administer',
                title: '操作管理员',
                align: 'center'
            }, {
                field: 'createTime',
                title: '操作时间',
                align: 'center'
            }, {
                field: 'record',
                title: '操作备注',
                align: 'center'
            }]
    });
}

$("#search").click(function () {
    var timeAdd = new Date($("#startTime").val());
    var timeEnd = new Date($("#endTime").val());
    if (timeAdd > timeEnd) {
        layer.msg("开始时间不能大于结束时间");
        return false;
    }
    $("#dataTable").bootstrapTable("refresh");
});

function queryParams(params) {
    var startTime;
    var endTime;
    if ($("#startTime").val().length > 0) {
        startTime = $("#startTime").val() + " 00:00:00"
    } else {
        startTime = $("#startTime").val()
    }
    if ($("#endTime").val().length > 0) {
        endTime = $("#endTime").val() + " 23:59:59"
    } else {
        endTime = $("#endTime").val()
    }
    return {
        size: params.pageSize,
        page: params.pageNumber,
        startTime: startTime,
        endTime: endTime,
        account: $.trim($("#account").val()),
        'userPm.name': $("#userPm").val(),
        status: $("#status").val(),
        auditType: $("#auditType").val(),
        supplyModel: $("#supplyModel").val(),
        type: $("#type").val(),
        include: $("#include").val(),
        userIds: $("#userIds").val(),
    };
}

$("#addUserSubmit").click(function () {
    var msg = $("#addUserModalLabel").attr("msg");
   
    var url;
    var v = $("#addUserForm").valid();
     console.log(">>",msg,"2.",v);
    if (!v) {
        return;
    }
    if (msg == 1) {
        url = "/UserController/insertSupUser"
    } else {
        url = "/UserController/updateSupUser"
    }
    $.ajax({
        type: "post",
        url: url,
        data: $("#addUserForm").serialize(),
        dataType: "json",
        async: false,
        cache: false,
        success: function (data) {
            if (data.success) {
                $("#dataTable").bootstrapTable("refresh");
                $("#addUserModal").modal("hide");
                layer.msg('操作成功');
            } else {
                layer.msg(data.message)
            }
        }
    });
})

function addUserFun(v) {
    $("#addUserModalLabel").attr("msg", v)
    $("#userKey").attr("readonly", "false");
    if (v == 1) {
        $("#userAccountUpdate").attr("readonly", false);
        $("#userNameUpdate").attr("readonly", false);
        $("#addUserModalLabel").text("新增会员信息");
        $("#addUserForm input,#addUserForm textarea").val("");
        addUserForm.resetForm();
        $("#userStatusAdd").val("POTENTIAL");
        $("#submitWay").val("WE_CHAT");
    } else {
        $("#addUserModalLabel").text("修改会员信息");
        // $("#userNameUpdate").attr("readonly", "false");
        var rows = $('#dataTable').bootstrapTable("getSelections");
        if (rows == null || rows.length == 0) {
            layer.msg("请选择要操作的数据");
            return;
        }
        if (rows.length > 1) {
            layer.msg("只能选择一个会员");
            return;
        }
        var row = rows[0];
        $("#hidId").val(row.userId);
        $("#userAccountUpdate").val(row.account);
        $("#notifyUrl").val(row.notifyUrl);
        $("#userStatus").val(row.status);
        $("#dailySupplyLimit").val(row.dailySupplyLimit);
        $("#entityLimit").val(row.entityLimit.toString());
        $("#apiState").val(row.apiState);
        if (row.userPm) {
            $("#userPmName").val(row.userPm.name);
        } else {
            $("#userPmName").val("");
        }
        $("#ip").val(row.ip);
        $("#userType").val(row.type);
        if (row.supInfo) {
            $("#userNameUpdate").val(row.supInfo.name);
            $("#area").val(row.supInfo.address);
            $("#realName").val(row.supInfo.realName);
            $("#phone").val(row.supInfo.phone);
            $("#qq").val(row.supInfo.qq);
            $("#wangwang").val(row.supInfo.wangwang);
            $("#email").val(row.supInfo.email);
            $("#idNumber").val(row.supInfo.idNumber);
            $("#idType").val(row.supInfo.idType);
            $("#remark").val(row.supInfo.remark);
        }
        $("#userKey").val(row.userKey);
        $("#editSupplyModel").val(row.supplyModel);
    }
    $("input[name=JSESSIONID]").val(sessionStorage.getItem('JSESSIONID'));
    $("#addUserModal").modal({backdrop: 'static', keyboard: false});
}

$("#updateUserSubmit").click(function () {
    $.ajax({
        type: "post",
        url: 'UserController/updatePrivilege',
        data: $("#updateUserForm").serialize(),
        dataType: "json",
        async: false,
        cache: false,
        success: function (data) {
            if (data.success) {
                $("#dataTable").bootstrapTable("refresh");
                $("#updateUserModal").modal("hide");
                layer.msg('操作成功');
            } else {
                layer.msg(data.message)
            }
        }
    });
})
$("#updateUserPrivilege").click(function updateUserPrivilege() {
    // $("#updateUserModalLabel").text("修改会员信息");
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows == null || rows.length === 0) {
        layer.msg("请选择要操作的数据");
        return;
    }
    var row = rows[0];
    $("#updateHidId").val(row.userId);
    $.post("UserController/queryPrivilege?userId=" + row.userId, null, function (data) {
        $("#supplyState").val(data.supplyState);
        $("#payPwdState").val(data.payPwdState);
        $("#businessOverview").val(data.businessOverview);
        $("#statisticReport").val(data.statisticReport);
        $("#virtualOperate").val(data.virtualOperate);
        $("#withdrawState").val(data.withdrawState);
        $("#postPaid").val(data.postPaid);
        $("#popUp").val(data.popUp);
        $("#alipayWithdraw").val(data.alipayWithdraw);
        $("#qbExchange").val(data.qbExchange);
    });
    $("input[name=JSESSIONID]").val(sessionStorage.getItem('JSESSIONID'));
    $("#updateUserModal").modal({backdrop: 'static', keyboard: false});
});

$("#resetUserLoginPwd").click(function () {
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows == null || rows.length === 0) {
        layer.msg("请选择要操作的数据");
        return;
    }
    var row = rows[0];
    $.confirm({
        title: '确认!',
        content: '确定要重置该会员登陆密码吗？',
        confirm: function () {
            $.post("/UserController/resetUserLoginPwd?userId="
                + row.userId, function (data) {
                layer.msg(data.message);
                $("#dataTable").bootstrapTable("refresh");
            });
        },
        cancel: function () {

        }
    });
});
$("#autoAsyn").click(function () {
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows == null || rows.length === 0) {
        layer.msg("请选择要操作的数据");
        return;
    }
    var row = rows[0];
    $.confirm({
        title: '确认!',
        content: '确定要开启' + row.supInfo.name + '自动异步吗？',
        confirm: function () {
            $.post("/UserController/autoAsyn?userId="
                + row.userId, function (data) {
                layer.msg(data.message);
            });
        },
        cancel: function () {

        }
    });
});
var userIds = [];

function updateUserStatus(privilege, status) {
    userIds = [];
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows == null || rows.length === 0) {
        layer.msg("请选择要操作的数据");
        return;
    }
    for (var i = 0; i < rows.length; i++) {
        userIds.push(rows[i].userId);
    }
    $.ajax({
        type: "post",
        url: '/UserController/updateUserStatus',
        traditional: true,
        data: {
            userIds: userIds,
            status: status,
            privilege: privilege
        },
        success: function (data) {
            if (data.success) {
                $("#dataTable").bootstrapTable("refresh");
                layer.msg('操作成功');
            } else {
                layer.msg(data.message)
            }
        }
    });
}

//闲鱼佣金展示状态
$('#commissionStatus').click(function (e) {
    var status;
    e.stopPropagation();
    var remind = "";
    var isOn = $('#commissioninclude').prop('checked');
    if (isOn) {
        remind = "关闭";
        status = 0
    } else {
        remind = "开启"
        status = 1
    }
    $.confirm({
        title: '确认!',
        content: '确定要在会员端【' + remind + '】闲鱼佣金页面吗？',
        confirm: function () {
            $.ajax({
                type: "POST",
                url: "/UserController/updateCommissionStatus",
                data: {
                    status: status
                },
                dataType: "json",
                success: function (data) {
                    if (data.success) {
                        layer.msg(data.message);
                        commissionStatusAuditGet();
                    } else {
                        layer.msg(data.message);
                        commissionStatusAuditGet();
                    }
                }
            })
        }
    })
})

//下载
$("#export").click(function () {
    window.location.href = "/UserController/downLoad?" + $("#userListForm").serialize()
})
$("#userKey").click(function () {
    $.confirm({
        title: '确认!',
        content: '确定要重置该会员的秘钥吗？',
        confirm: function () {
            $.post("/UserController/getUserKey", function (data) {
                $("#userKey").val(data);
            });
        },
        cancel: function () {

        }
    });
})
$("#updateEquityCredit").click(function () {
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows == null || rows.length === 0) {
        layer.msg("请选择要操作的数据");
        return;
    }
    $("#updateEquityCreditModal").modal("show");
})
$("#updateEquityCreditSubmit").click(function () {
    userIds = [];
    var rows = $('#dataTable').bootstrapTable("getSelections");
    if (rows == null || rows.length === 0) {
        layer.msg("请选择要操作的数据");
        return;
    }
    for (var i = 0; i < rows.length; i++) {
        userIds.push(rows[i].userId);
    }
    $.ajax({
        type: "post",
        url: '/UserController/updateEquityCredit',
        traditional: true,
        data: {
            userIds: userIds,
            equityCredit: $("#equityCredit").val(),
            remark: $("#editRemark").val(),

        },
        success: function (data) {
            if (data.success) {
                $("#dataTable").bootstrapTable("refresh");
                layer.msg('操作成功');
                $("#equityCredit").val(""),
                    $("#editRemark").val(""),
                    $("#updateEquityCreditModal").modal("hide");
            } else {
                layer.msg(data.message)
            }
        }
    });
})

//获取佣金展示状态
function commissionStatusAuditGet() {
    $.ajax({
        type: "POST",
        url: "/UserController/getCommissionStatus",
        success: function (data) {
            if (data) {
                $('#commissioninclude').bootstrapToggle('on');
            } else {
                $('#commissioninclude').bootstrapToggle('off');
            }
        }
    });
}

//审核供卡申请
function fixSubmitApply(userId) {
    $("#cardApplyForm [name=userId]").val(userId);
    $("#cardApplyForm [name=apply]").val("");
    $("#cardApplyForm [name=remark]").val("");
    $("#cardApplyModal").modal("show");
}

$("#cardApplySubmit").click(function () {
    var userId = $("#cardApplyForm [name=userId]").val();
    if (!userId) {
        layer.msg('请选择操作会员');
        return false;
    }
    var apply = $("#cardApplyForm [name=apply]").val();
    if (!apply) {
        layer.msg('请选择审核状态');
        return false;
    }
    $.ajax({
        type: "post",
        url: 'UserController/auditSubmitCardApply',
        data: {
            userId: userId,
            apply: apply,
            remark: $("#cardApplyForm input[name=remark]").val(),
        },
        dataType: "json",
        async: false,
        cache: false,
        success: function (data) {
            if (data.success) {
                $("#dataTable").bootstrapTable("refresh");
                $("#cardApplyModal").modal("hide");
                layer.msg('操作成功');
            } else {
                layer.msg(data.message)
            }
        }
    });
});